package com.client.controller.auth;

import com.client.entity.PassAuthor;
import com.client.mapper.AuthorityDao;
import com.client.mapper.CommandDao;
import com.client.mapper.OperatorDao;
import com.client.mapper.PassAuthorDao;
import com.client.service.MessageService;
import com.client.utils.UDPUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Component
public class DeviceManagement {

    @Autowired
    AuthorityDao authorityDao;
    @Autowired
    CommandDao commandDao;
    @Autowired
    OperatorDao operatorDao;
    @Autowired
    PassAuthorDao passAuthorDao;
    @Autowired
    UDPUtil udp;
    @Value("${id}")
    String my_id;

    //处理平台的权限更新命令
    @ServiceActivator(inputChannel = "Device-Rights-Management")
    public void udpMessageHandle1(Map<String, Object> map) {
        String id = (String) map.get("b_id");
        if (!id.equals("Certification"))
            return;
        List<String> operators = (List<String>) map.get("operators");    //该设备的管理人员
        List<String> commands = (List<String>) map.get("commands");    //该设备的操作命令

        //删除原有权限数据
        authorityDao.deleteAll();
        commandDao.deleteAll();
        operatorDao.deleteAll();

        //添加数据
        int i=1;
        for (String operator : operators) {
            operatorDao.add(i++, operator);
        }
        i=1;
        for (String command : commands) {
            commandDao.add(i++,  command,"无");
        }

        i=1;
        for (String operator : operators) {
            List<Integer> authorities = (List<Integer>) map.get(operator);

            for (Integer authority : authorities) {

                authorityDao.add(i++, operators.indexOf(operator)+1, authority);
            }
        }
        //通知设备管理平台修改成功
        PassAuthor certification = passAuthorDao.queryByName("Certification");
        byte[] bytes = MessageService.MessageConfirm(certification.getK(),
                (UUID) map.get("b_uid"),my_id );
        udp.send(certification.getIp(), certification.getPort(), bytes);
        log.info("已通知设备管理平台权限信息更新成功");
    }

    //处理对方的确认信息
    @ServiceActivator(inputChannel = "CONFIRM_GET_PACKET")
    public void confirm_get_packet(Map<String, Object> map){
        UUID uid = (UUID) map.get("uid");
        MessageService.deleteMessage(uid.toString());
        log.info("对方已经收到了我们发送的消息");
    }

}
